package com.zb;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池的四种拒绝策略 并且提供spi机制 让用户支持自定义拒绝策略
 */
public class RejectedPolicyRegistry {
    private static final Map<String, RejectedExecutionHandler> POLICIES = new HashMap<>();

    static {
        POLICIES.put("AbortPolicy", new ThreadPoolExecutor.AbortPolicy());
        POLICIES.put("CallerRunsPolicy", new ThreadPoolExecutor.CallerRunsPolicy());
        POLICIES.put("DiscardOldestPolicy", new ThreadPoolExecutor.DiscardOldestPolicy());
        POLICIES.put("DiscardPolicy", new ThreadPoolExecutor.DiscardPolicy());
    }

    public static void register(String name, RejectedExecutionHandler policy) {
        POLICIES.put(name, policy);
    }

    public static RejectedExecutionHandler getPolicy(String key) {
        if (POLICIES.containsKey(key)) {
            return POLICIES.get(key);
        }
        try {
            Class<?> clazz = Class.forName(key);
            return (RejectedExecutionHandler) clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("拒绝策略不存在：" + key, e);
        }
    }
}